import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Router} from '@angular/router';
import {ServiceLogicService} from '../../service/service-logic.service';
import {Admin} from '../../domain/admin';

// import {OutRecord} from '../../domain/admin';


@Component({
  selector: 'app-manage',
  templateUrl: './manage.component.html',
  styleUrls: ['./manage.component.css']
})
export class ManageComponent implements OnInit {
  displayDialog: boolean;
  selectedAdmin: Admin;
  newAdmin: boolean;
  private data: any;
  cols: any[];
  // approved_outRecords: Admin[];
  // rejectAndPass_outRecords: Admin[];
  admins: Admin[];
  admin: Admin = {};
  onRowSelect(event) {
    this.newAdmin = false;
    this.admin = this.cloneOutRecord(event.data);
    this.displayDialog = true;
  }
  showDialogToAdd() {
    this.newAdmin = true;
    this.admin = {};
    this.displayDialog = true;
  }
  save() {
    const outRecords = [...this.admins];
    if (this.newAdmin) {
      outRecords.push(this.admin);
      console.log(this.admin);
      console.log(12);
      console.log(this.admin);
      this.admin.admin_state = parseInt(this.admin.admin_state, 0);
      // this.outRecord.state = 1;
      // this.outRecord.des = '审核中';
      // this.outRecord.admin_id = this.data.admin_id;
      this.logicService.addAdmin(this.admin).then(res => {console.log(123); console.log(this.admin); });
      // 在这里像数据库写入数据。
    } else {
      outRecords[this.admins.indexOf(this.selectedAdmin)] = this.admin;
      this.logicService.updateAdmin(this.admin).then(() => {});
      console.log(this.admin);
    }
    this.admins = outRecords;
    this.admin = null;
    this.displayDialog = false;
  }
  delete() {
    const index = this.admins.indexOf(this.selectedAdmin);
    this.logicService.deleteAdmin(this.admins[index].id).then(() => {
      this.admins = this.admins.filter((nmnm, i) => i !== index);
    });
    // 通过outRecords[this.outRecords.indexOf(this.selectedOutRecord)]删除数据库数据
    // console.log(index);
    // console.log(this.outRecords);
    this.admin = null;
    this.displayDialog = false;
  }
  cloneOutRecord(c: Admin): Admin {
    const outRecord = {};
    for (const prop in c) {
      if (c.hasOwnProperty(prop)) {
        outRecord[prop] = c[prop];
      }
    }
    return outRecord;
  }
  constructor(public activateRoute: ActivatedRoute, public router: Router, private logicService: ServiceLogicService) { }
  private get() {
    return this.data;
  }
  ngOnInit() {
    this.data = this.activateRoute.snapshot.params;
    this.logicService.getAdmin(this.data.admin_state).then(res => {console.log(res); this.admins = res; });
    this.cols = [
      {field: 'admin_id', header: 'admin_id'},
      {field: 'admin_name', header: 'admin_name'},
      {field: 'admin_pwd', header: 'admin_pwd'},
      {field: 'admin_state', header: 'admin_state'},
    ];
  }

}
